/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2011
Version 0.1
=======================================================*/
DeviceMoveWindow = function(device) {
	this.device = device;
	
	this.type = 0;
	
	this.groupList = new Ext.list.ListView({
		fieldLabel: 'Group List',
    	height: 300,
    	autoScroll: true,
    	multiSelect: true,
	 	hideHeaders: true,
	 	msgTarget: 'under',
    	style: 'background:#ffffff;',
		store: new Ext.data.ArrayStore({fields: ['Name','Group']}),
	    columns: [{header: 'Group List', dataIndex: 'Name'}]});

    this.form = new Ext.FormPanel({
        labelAlign:'top',
        items: [this.groupList],
        border: false,
        fileApply: true,
        bodyStyle:'background:transparent;padding:10px;'
    });

	DeviceMoveWindow.superclass.constructor.call(this, {
        title: 'Move device',
        iconCls: 'move-device-icon',
        autoHeight: true,
        width: 400,
        resizable: false,
        plain:true,
        modal: true,
        y: 100,
        autoScroll: false,
        closeAction: 'hide',

        buttons:[{
            text: 'Move',
            handler: this.onMove,
            scope: this
        },{
            text: 'Cancel',
            handler: this.hide.createDelegate(this, [])
        }],

        items: this.form
    });
}

Ext.extend(DeviceMoveWindow, Ext.Window, {
    show: function() {
   		this.populateGroups();
        ConfigurationWindow.superclass.show.apply(this, arguments);
    },
    
    populateGroups : function(){
		SGui.getGroups(this.cbPopulateGroups,this);
	},

	cbPopulateGroups : function(obj,result){
		obj.groupList.store.removeAll();
		if(result)
		{
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++){
					var group = new Group(result[i]);
					if(group.id != obj.device.groupID)
						obj.groupList.store.loadData([[group.name,group]],true);
				}
			} else {
				var group = new Group(result);
				if(group.id != obj.device.groupID)
					obj.groupList.store.loadData([[group.name,group]],true);
			}
		}
	},    

    onMove: function() {
    	var records = this.groupList.getSelectedRecords();

    	if(records.length == 0) {
    		this.groupList.markInvalid("You must have selected at least one group!");
    		return;
    	}

    	this.el.mask('Moving device...', 'x-mask-loading');
		SGui.moveDeviceToGroup(this.device.id,records[0].get('Group').id,this.csMove,this);    	
    },

    csMove: function(obj,result) {
		obj.el.unmask();

    	if(result instanceof Array && result[0] == '-1') {
    		Ext.MessageBox.show({title: 'Error', msg: 'Invalid device.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
    	} else {
		    obj.hide();
			obj.fireEvent('moveDevice');
    	}
    }
});
